package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest Request, ServletResponse Response, FilterChain chain) throws ServletException, IOException {
        String[] loginUrls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"};
        HttpServletRequest request = (HttpServletRequest) Request;
        HttpServletResponse response = (HttpServletResponse) Response;

        String requestURI = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();

        for (String loginUrl : loginUrls) {
            boolean match = antPathMatcher.match(loginUrl, requestURI);
            if (match) {
                chain.doFilter(request, response);
                return;
            }
        }
        HttpSession session = request.getSession();
        Long loginEmployee = (Long) session.getAttribute("loginEmployee");
        if (loginEmployee != null) {
            BaseContext.setCurrentId(loginEmployee);
            chain.doFilter(request, response);
            BaseContext.remove();
            return;
        }

        if (request.getSession().getAttribute("user") != null) {
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            log.info("{}", userId);
            chain.doFilter(request, response);
            BaseContext.remove();
            return;
        }
        R<String> notlogin = R.error("NOTLOGIN");
        String jsonString = JSON.toJSONString(notlogin);
        response.getWriter().write(jsonString);
    }
}
